/*
 * Created on 2005-3-3
 */
package com.hd123.rumba.user;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import net.sf.hibernate.FlushMode;
import net.sf.hibernate.Hibernate;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.ReplicationMode;
import net.sf.hibernate.type.Type;

import com.hd123.rumba.domain.CDomain;
import com.hd123.rumba.domain.IDomain;
import com.hd123.rumba.domain.IDomainFuncView;
import com.hd123.rumba.domain.IDomainMgr;
import com.hd123.rumba.exception.BusinessException;
import com.hd123.rumba.exception.DuplicateIdException;
import com.hd123.rumba.exception.ParameterException;
import com.hd123.rumba.log.EntityLogger;
import com.hd123.rumba.organization.IOrganization;
import com.hd123.rumba.organization.IOrganizationMgr;
import com.hd123.rumba.runtime.IAfterSave;
import com.hd123.rumba.runtime.IAfterSaveNew;
import com.hd123.rumba.runtime.Manager;
import com.hd123.rumba.runtime.NamingMgr;
import com.hd123.rumba.runtime.ObserverRegistry;
import com.hd123.rumba.runtime.OperateContext;
import com.hd123.rumba.sql.ResultPage;
import com.hd123.rumba.sql.SQLSubquery;
import com.hd123.rumba.user.token.TokenConstants;
import com.hd123.rumba.util.Iterators;
import com.hd123.rumba.util.ObjectUtil;
import com.hd123.rumba.util.SecurityUtil;

/**
 * @author caili
 */
public class UserMgr extends Manager implements IUserMgr {

  public static final String CAPTION_MANAGER = "用户管理员";

  public UserMgr() {
    super();
    this.registryClass("com.hd123.rumba.user.IUser", "com.hd123.rumba.user.User");
    this.registryClass("com.hd123.rumba.user.IUserRole", "com.hd123.rumba.user.UserRole");
    this.registryClass("com.hd123.rumba.user.IUserPermission",
        "com.hd123.rumba.user.UserPermission");
  }

  public IUser createUser(IDomain domain, String login) throws HibernateException,
      BusinessException {
    checkParameterNotNull(domain, "domain");
    checkParameterNotNull(login, "login");
    IUser user = getUserByLogin(domain, login);
    if (user != null)
      throw new DuplicateIdException("域" + domain.getCode() + "中已经存在" + CUser.CAPTION_LOGIN + "为"
          + login + "的用户");

    user = new User();
    user.setDomain(domain);
    user.setState(CUser.VALUE_STATE_NORMAL);
    user.setOnline(Boolean.TRUE);
    user.setLogin(login);
    return user;
  }

  public IUser createUser(IDomain domain) throws BusinessException, HibernateException {
    checkParameterNotNull(domain, "domain");
    IUser user = new User();
    user.setDomain(domain);
    user.setState(CUser.VALUE_STATE_NORMAL);
    user.setOnline(Boolean.TRUE);
    return user;
  }

  public IUser getUserByLogin(IDomain domain, String login) throws HibernateException,
      BusinessException {
    checkParameterNotNull(domain, "domain");
    IUser user = null;
    if (login != null) {
      List list = getSession().find(
          "from User u where u.login = ? and u.domain.uuid = ? and u.state <> ?", new Object[] {
              login.toUpperCase(), domain.getUuid(), CUser.VALUE_STATE_DELETED }, new Type[] {
              Hibernate.STRING, Hibernate.STRING, Hibernate.INTEGER });
      if (list.size() > 0) {
        user = (IUser) list.get(0);
      }
    }
    return user;
  }

  public IUser getUser(String uuid) throws BusinessException, HibernateException {
    return getUser(uuid, null);
  }

  public IUser getUser(String uuid, Integer[] states) throws HibernateException, BusinessException {
    if (uuid == null)
      return null;
    if (uuid.equals(this.sysUser.getUuid()))
      return this.sysUser;
    IUser user = (IUser) getSession().get(IUser.class, uuid);
    if (states == null)
      return user;
    for (int i = 0; i < states.length; i++)
      if (states[i] != null && states[i].equals(user.getState()))
        return user;
    return null;
  }

  public IUser getValidUser(String uuid) throws BusinessException, HibernateException {
    return getUser(uuid, new Integer[] {
      CUser.VALUE_STATE_NORMAL });
  }

  /** @deprecated */
  public void saveUser(IUser user) throws HibernateException, BusinessException {
    saveUser(user, getSysUser(), user.getOca());
  }

  /** @deprecated */
  public void saveUser(IUser user, IUser operator, long oca) throws BusinessException,
      HibernateException {
    saveUser(user, new OperateContext(operator));
  }

  public void saveUser(IUser user, OperateContext operate) throws BusinessException,
      HibernateException {
    checkParameterNotNull(user, "user");
    checkParameterNotNull(operate, "operate");

    if (user.equals(sysUser))
      throw new BusinessException("禁止保存用户:" + sysUser.getNameCode() + "。");
    if (user.getUuid() == null || !CUser.VALUE_STATE_DELETED.equals(user.getState())) {
      getSession().setFlushMode(FlushMode.COMMIT);
      IDomain domain = user.getDomain();
      IUser euser = getUserByLogin(domain, user.getLogin());
      if (euser != null && !euser.equals(user))
        throw new DuplicateIdException("域" + domain.getCode() + "中已经存在" + CUser.CAPTION_LOGIN + "为"
            + euser.getLogin() + "的用户");
    }

    Date operTime = operate.getTime();
    EntityLogger logger = new EntityLogger(this);
    logger.setEntity(user);
    logger.setEntityConstClass(IUser.class);
    logger.setOperator(operate.getOperator());
    logger.setTime(operTime);

    boolean isNew = user.getUuid() == null;
    user.setLastModified(operTime);
    user.setLastModifier(operate.getOperator().getNameCode());
    getSession().saveOrUpdate(user);

    if (isNew)
      ObserverRegistry.notifyObservers(IAfterSaveNew.class, user);
    else
      ObserverRegistry.notifyObservers(IAfterSave.class, user);

    if (isNew)
      logger.log(EntityLogger.EVENT_ADDNEW, user.getState(), CUser.CAPTION_CLASS + ":"
          + user.getNameCode());
    else
      logger.log(EntityLogger.EVENT_MODIFY, user.getState(), CUser.CAPTION_CLASS + ":"
          + user.getNameCode());
  }

  public void saveUserWithUuid(IUser user, OperateContext operate) throws BusinessException,
      HibernateException {
    ObjectUtil.checkParameterNotNull(user, "user");
    ObjectUtil.checkParameterNotNull(operate, "operate");

    if (user.equals(sysUser))
      throw new BusinessException("禁止保存用户:" + sysUser.getNameCode() + "。");
    if (user.getUuid() == null || !CUser.VALUE_STATE_DELETED.equals(user.getState())) {
      getSession().setFlushMode(FlushMode.COMMIT);
      IDomain domain = user.getDomain();
      IUser euser = getUserByLogin(domain, user.getLogin());
      if (euser != null && !euser.equals(user))
        throw new DuplicateIdException("域" + domain.getCode() + "中已经存在" + CUser.CAPTION_LOGIN + "为"
            + euser.getLogin() + "的用户");
    }

    Date operTime = operate.getTime();
    EntityLogger logger = new EntityLogger(this);
    logger.setEntity(user);
    logger.setEntityConstClass(IUser.class);
    logger.setOperator(operate.getOperator());
    logger.setTime(operTime);

    user.setLastModified(operTime);
    user.setLastModifier(operate.getOperator().getNameCode());

    if (user.getProfile() == null)
      user.setProfile(new Profile());
    getSession().saveOrUpdate(user.getProfile());
    getSession().replicate(user, ReplicationMode.OVERWRITE);

    ObserverRegistry.notifyObservers(IAfterSave.class, user);

    logger.log(EntityLogger.EVENT_MODIFY, user.getState(), CUser.CAPTION_CLASS + ":"
        + user.getNameCode());
  }

  public void deleteUser(IUser user, OperateContext operate) throws BusinessException,
      HibernateException {
    checkParameterNotNull(user, "user");
    checkParameterNotNull(operate, "operate");

    if (user.equals(sysUser))
      throw new BusinessException("禁止修改用户:" + sysUser.getNameCode() + "。");

    Date operTime = operate.getTime();
    EntityLogger logger = new EntityLogger(this);
    logger.setEntity(user);
    logger.setEntityConstClass(IUser.class);
    logger.setOperator(operate.getOperator());
    logger.setTime(operTime);
    logger.log("删除用户", CUser.VALUE_STATE_DELETED, CUser.CAPTION_CLASS + ":" + user.getNameCode());

    user.setState(CUser.VALUE_STATE_DELETED);
    user.setLastModified(operTime);
    user.setLastModifier(operate.getOperator().getNameCode());
    getSession().saveOrUpdate(user);
  }

  public void undeleteUser(IUser user, OperateContext operate) throws BusinessException,
      HibernateException {
    checkParameterNotNull(user, "user");
    checkParameterNotNull(operate, "operate");

    if (user.equals(sysUser))
      throw new BusinessException("禁止修改用户:" + sysUser.getNameCode() + "。");
    if (CUser.VALUE_STATE_DELETED.equals(user.getState())) {
      getSession().setFlushMode(FlushMode.COMMIT);
      IDomain domain = user.getDomain();
      IUser user2 = this.getUserByLogin(domain, user.getLogin());
      if (user2 != null)
        throw new DuplicateIdException("域" + domain.getNameCode() + "中已经存在" + CUser.CAPTION_LOGIN
            + "为\"" + user.getLogin() + "\"的角色。");
    }

    Date operTime = operate.getTime();
    EntityLogger logger = new EntityLogger(this);
    logger.setEntity(user);
    logger.setEntityConstClass(IUser.class);
    logger.setOperator(operate.getOperator());
    logger.setTime(operTime);
    logger.log("恢复已删除用户", CUser.VALUE_STATE_NORMAL, CUser.CAPTION_CLASS + ":" + user.getNameCode());

    user.setState(CUser.VALUE_STATE_NORMAL);
    user.setLastModified(operTime);
    user.setLastModifier(operate.getOperator().getNameCode());
    getSession().saveOrUpdate(user);
  }

  public void removeUser(IUser user) throws HibernateException, BusinessException {
    checkParameterNotNull(user, "user");
    if (user.equals(sysUser))
      throw new BusinessException("禁止删除用户:" + sysUser.getNameCode() + "。");
    getSession().delete("from UserPermission up where up.user.uuid=?", user.getUuid(),
        Hibernate.STRING);
    getSession().delete("from UserRole ur where ur.user.uuid=?", user.getUuid(), Hibernate.STRING);
    getSession().delete("from PermissionCommission pc where pc.fromUser.uuid=?", user.getUuid(),
        Hibernate.STRING);
    getSession().delete("from PermissionCommission pc where pc.toUser.uuid=?", user.getUuid(),
        Hibernate.STRING);
    getSession().delete(user);
  }

  public List createAllUsersList(IDomain domain) throws HibernateException, BusinessException {
    checkParameterNotNull(domain, "domain");
    return getSession().find("from User u where u.domain.uuid=? order by u.login",
        domain.getUuid(), Hibernate.STRING);
  }

  public ResultPage createAllUsersPage(IDomain domain, int pageSize, int page) throws Exception,
      BusinessException {
    checkParameterNotNull(domain, "domain");
    SQLSubquery sq = new SQLSubquery();
    sq.addSelect("u");
    sq.addFrom("User", "u");
    sq.addWhere("u.domain.uuid=?", domain.getUuid());
    sq.addOrder("u.login");
    return ResultPage.createHibernateResultPage(getSession(), sq, pageSize, page);
  }

  /** @deprecated */
  public void assignPermissionToUser(IPermission perm, IUser user) throws HibernateException,
      BusinessException {
    assignPermissionToUser(perm, user, new OperateContext(getSysUser()));
  }

  public void assignPermissionToUser(IPermission perm, IUser user, OperateContext operate)
      throws HibernateException, BusinessException {
    checkParameterNotNull(perm, "perm");
    checkParameterNotNull(user, "user");
    checkParameterNotNull(operate, "operate");
    if (user.equals(sysUser))
      throw new BusinessException("禁止修改用户:" + sysUser.getNameCode() + "。");
    if (!hasPermission(user, perm)) {
      IUserPermission up = new UserPermission();
      up.setPermission(perm);
      up.setUser(user);
      getSession().save(up);

      EntityLogger logger = new EntityLogger(this);
      logger.setEntity(user);
      logger.setEntityConstClass(IUser.class);
      logger.setOperator(operate.getOperator());
      logger.setTime(operate.getTime());
      logger.log(EVENT_ASSIGNPERMISSION, user.getState(), CPermission.CAPTION_CLASS + ":"
          + perm.getCode());
    }
  }

  public boolean hasPermission(IUser user, IPermission perm) throws HibernateException,
      BusinessException {
    checkParameterNotNull(perm, "perm");
    checkParameterNotNull(user, "user");
    List list = getSession().find(
        "from UserPermission up where up.user.uuid=? and up.permission.uuid=?", new Object[] {
            user.getUuid(), perm.getUuid() }, new Type[] {
            Hibernate.STRING, Hibernate.STRING });
    return list.size() > 0;
  }

  /** @deprecated */
  public void removePermissionFromUser(IPermission perm, IUser user) throws HibernateException,
      BusinessException {
    removePermissionFromUser(perm, user, new OperateContext(getSysUser()));
  }

  public void removePermissionFromUser(IPermission perm, IUser user, OperateContext operate)
      throws HibernateException, BusinessException {
    checkParameterNotNull(perm, "perm");
    checkParameterNotNull(user, "user");
    checkParameterNotNull(operate, "operate");
    if (user.equals(sysUser))
      throw new BusinessException("禁止修改用户:" + sysUser.getNameCode() + "。");
    getSession().delete(
        "from UserPermission as up where up.permission.uuid = ? and up.user.uuid = ?",
        new Object[] {
            perm.getUuid(), user.getUuid() }, new Type[] {
            Hibernate.STRING, Hibernate.STRING });

    EntityLogger logger = new EntityLogger(this);
    logger.setEntity(user);
    logger.setEntityConstClass(IUser.class);
    logger.setOperator(operate.getOperator());
    logger.setTime(operate.getTime());
    logger.log(EVENT_REMOVEPERMISSION, user.getState(), CPermission.CAPTION_CLASS + ":"
        + perm.getCode());
  }

  /**
   * 返回user固有的权限列表. 直接的权限, 不包括通过角色得到的权限.
   * 
   * @param user
   * @return List of IPermission
   * @throws HibernateException
   * @throws ParameterException
   */
  public List createPermissionsList(IUser user) throws HibernateException, BusinessException {
    checkParameterNotNull(user, "user");
    IDomainMgr dmMgr = (IDomainMgr) NamingMgr.getInstance().lookupMgr(IDomainMgr.class);
    return getSession().find(
        "select p from " + UserPermission.class.getName() + " as up"
            + " inner join up.permission as p, " + dmMgr.lookupClass(IDomainFuncView.class)
            + " dfv" + " where dfv.funcView.uuid = p.cartFuncViewUuid" + " and dfv.domain.uuid = ?"
            + " and up.user.uuid = ?" + " order by p.code", new Object[] {
            user.getDomain().getUuid(), user.getUuid() }, new Type[] {
            Hibernate.STRING, Hibernate.STRING });
  }

  /** @deprecated */
  public void assignRoleToUser(IRole role, IUser user) throws HibernateException, BusinessException {
    assignRoleToUser(role, user, new OperateContext(getSysUser()));
  }

  public void assignRoleToUser(IRole role, IUser user, OperateContext operate)
      throws HibernateException, BusinessException {
    checkParameterNotNull(role, "role");
    checkParameterNotNull(user, "user");
    checkParameterNotNull(operate, "operate");
    if (user.equals(sysUser))
      throw new BusinessException("禁止修改用户:" + sysUser.getNameCode() + "。");
    if (!hasRole(user, role)) {
      IUserRole ur = new UserRole();
      ur.setRole(role);
      ur.setUser(user);
      getSession().save(ur);

      EntityLogger logger = new EntityLogger(this);
      logger.setEntity(user);
      logger.setEntityConstClass(IUser.class);
      logger.setOperator(operate.getOperator());
      logger.setTime(operate.getTime());
      logger.log(EVENT_ASSIGNROLE, user.getState(), CRole.CAPTION_CLASS + ":" + role.getNameCode());
    }
  }

  public boolean hasRole(IUser user, IRole role) throws HibernateException, BusinessException {
    checkParameterNotNull(role, "role");
    checkParameterNotNull(user, "user");
    List list = getSession().find(
        "from UserRole ur where ur.user.uuid = ? and ur.role.uuid = ? and ur.role.state <> ?",
        new Object[] {
            user.getUuid(), role.getUuid(), CRole.VALUE_STATE_DELETED }, new Type[] {
            Hibernate.STRING, Hibernate.STRING, Hibernate.INTEGER });
    return list.size() > 0;
  }

  /** @deprecated */
  public void removeRoleFromUser(IRole role, IUser user) throws HibernateException,
      BusinessException {
    this.removeRoleFromUser(role, user, new OperateContext(sysUser));
  }

  public void removeRoleFromUser(IRole role, IUser user, OperateContext operate)
      throws HibernateException, BusinessException {
    checkParameterNotNull(role, "role");
    checkParameterNotNull(user, "user");
    checkParameterNotNull(operate, "operate");
    if (user.equals(sysUser))
      throw new BusinessException("禁止修改用户:" + sysUser.getNameCode() + "。");
    getSession().delete("from UserRole as ur where ur.role.uuid = ? and ur.user.uuid = ?",
        new Object[] {
            role.getUuid(), user.getUuid() }, new Type[] {
            Hibernate.STRING, Hibernate.STRING });

    EntityLogger logger = new EntityLogger(this);
    logger.setEntity(user);
    logger.setEntityConstClass(IUser.class);
    logger.setOperator(operate.getOperator());
    logger.setTime(operate.getTime());
    logger.log(EVENT_REMOVEROLE, user.getState(), CRole.CAPTION_CLASS + ":" + role.getNameCode());
  }

  /**
   * @param user
   * @return List of IRole
   * @throws HibernateException
   * @throws ParameterException
   */
  public List createRolesList(IUser user) throws HibernateException, BusinessException {
    return getSession().find(
        "select r from Role as r, UserRole as ur "
            + " where r.uuid = ur.role.uuid and ur.user.uuid = ? and r.state <> ? order by r.code",
        new Object[] {
            user.getUuid(), CRole.VALUE_STATE_DELETED }, new Type[] {
            Hibernate.STRING, Hibernate.INTEGER });
  }

  /**
   * 取得user通过授权得到的PermissionCommission
   * 
   * @param user
   * @return List of IPermissionCommission
   * @throws HibernateException
   */
  public List createCommissionedPermissionsList(IUser user) throws HibernateException,
      BusinessException {
    return getSession().find(
        "select pc from PermissionCommission pc where pc.toUser.uuid=? order by pc.fromUser.uuid",
        user.getUuid(), Hibernate.STRING);
  }

  /**
   * 取得fromUser授权给toUser的权限授权列表
   * 
   * @param fromUser
   * @param toUser
   * @return List of IPermissionCommission
   * @throws HibernateException
   */
  public List createCommissionedPermissionsList(IUser fromUser, IUser toUser)
      throws HibernateException, BusinessException {
    checkParameterNotNull(fromUser, "fromUser");
    checkParameterNotNull(toUser, "toUser");
    if (toUser.equals(sysUser))
      throw new BusinessException("禁止修改用户:" + sysUser.getNameCode() + "。");
    return getSession().find(
        "select pc from PermissionCommission pc where pc.toUser.uuid=? and pc.fromUser.uuid=?",
        new Object[] {
            toUser.getUuid(), fromUser.getUuid() }, new Type[] {
            Hibernate.STRING, Hibernate.STRING });
  }

  /**
   * 取得user授出的PermissionCommission
   * 
   * @param user
   * @return List of IPermissionCommission
   * @throws HibernateException
   */
  public List createCommissionPermissionsList(IUser user) throws HibernateException,
      BusinessException {
    checkParameterNotNull(user, "user");
    return getSession().find(
        "select pc from PermissionCommission pc where pc.fromUser.uuid=? order by pc.toUser.uuid",
        user.getUuid(), Hibernate.STRING);
  }

  /**
   * 授权. fromUser必须具有分配的(不是授权得到的)权限perm. 所有的参数都是必须的.
   * 
   * @param fromUser
   * @param toUser
   * @param validFrom
   * @param validTo
   * @param perm
   * @return boolean 表示成功或失败.
   * @throws ParameterException
   * @throws HibernateException
   */
  public boolean grantPermission(IUser fromUser, IUser toUser, Date validFrom, Date validTo,
      IPermission perm) throws BusinessException, HibernateException {
    checkParameterNotNull(fromUser, "fromUser");
    checkParameterNotNull(toUser, "toUser");
    checkParameterNotNull(validFrom, "validFrom");
    checkParameterNotNull(validTo, "validTo");
    checkParameterNotNull(perm, "perm");
    if (toUser.equals(sysUser))
      throw new BusinessException("禁止修改用户:" + sysUser.getNameCode() + "。");
    if (fromUser.hasAssignedPermission(perm.getCode())) {
      IPermissionCommission pc = new PermissionCommission();
      pc.setFromUser(fromUser);
      pc.setToUser(toUser);
      pc.setPermission(perm);
      pc.setValidFrom(validFrom);
      pc.setValidTo(validTo);
      getSession().save(pc);
      return true;
    }
    return false;
  }

  public void revokePermission(IUser fromUser, IUser toUser, IPermission perm)
      throws HibernateException, BusinessException {
    checkParameterNotNull(fromUser, "fromUser");
    checkParameterNotNull(toUser, "toUser");
    checkParameterNotNull(perm, "perm");
    if (toUser.equals(sysUser))
      throw new BusinessException("禁止修改用户:" + sysUser.getNameCode() + "。");
    getSession().delete(
        "from PermissionCommission pc " + "where pc.fromUser.uuid=? and pc.toUser.uuid=? "
            + "and pc.permission.uuid=?", new Object[] {
            fromUser.getUuid(), toUser.getUuid(), perm.getUuid() }, new Type[] {
            Hibernate.STRING, Hibernate.STRING, Hibernate.STRING });
  }

  /**
   * 返回具有给定权限的用户集. 这里的权限是固有权限, 不包括授权的权限.
   * 
   * @param permissionId
   * @return Iterator of IUser
   */
  public Iterator createUsersHavingPermissionIdIterator(String permissionCode)
      throws HibernateException, BusinessException {
    IPermission perm = ((IPermissionMgr) NamingMgr.getInstance().lookupMgr(IPermissionMgr.class))
        .getPermissionByCode(permissionCode);
    if (perm == null)
      return Iterators.createEmptyIterator();
    // 直接具有权限的: UserPermission
    List user1 = getSession().find(
        "select up.user from UserPermission as up where up.permission.uuid=?", perm.getUuid(),
        Hibernate.STRING);
    // 通过角色具有权限的UserRole, RolePermission
    List user2 = getSession().find(
        "select ur.user " + "from UserRole as ur, RolePermission as rp "
            + "where ur.role = rp.role and rp.permission.uuid=?", perm.getUuid(), Hibernate.STRING);
    user1.addAll(user2);
    return Iterators.createIterator(user1);
  }

  public LoginResult login(String login, String password, String domainCode) {
    LoginResult result = new LoginResult();
    try {
      IDomain domain = ((IDomainMgr) NamingMgr.getInstance().lookupMgr(IDomainMgr.class))
          .getDomainByCode(domainCode);
      if (domain == null) {
        result.addErrorText("登录的组织(域)" + domainCode + "不存在。请联系管理员。");
        return result;
      }
      if (CDomain.VALUE_STATE_DELETED.equals(domain.getState())) {
        result.addErrorText("登录的组织(域)状态" + CDomain.CAPTION_VALUE_STATE_DELETED + "。请联系管理员。");
        return result;
      }
      IUser user = getUserByLogin(domain, login);
      if (user == null) {
        result.addErrorText("登录名" + login + "不存在。");
        return result;
      }
      if (Boolean.FALSE.equals(user.getOnline())) {
        result.addErrorText("用户" + login + "已被禁用。");
        return result;
      }
      if (!((user.getPassword() == null && (password == null || password.length() == 0)) || (user
          .getPassword() != null && user.getPassword().equals(SecurityUtil.encodeString(password))))) {
        result.addErrorText("密码不正确. 密码区分大小写字母.");
        return result;
      }
      result.setUser(user);
      result.setDomain(domain);
      IDomain enterpriseDomain = domain.getDomain();
      if (enterpriseDomain == null)
        enterpriseDomain = domain;
      enterpriseDomain.getDomain();
      result.setEnterpriseDomain(enterpriseDomain);

      IOrganizationMgr orgMgr = (IOrganizationMgr) NamingMgr.getInstance().lookupMgr(
          IOrganizationMgr.class);
      IOrganization org = orgMgr.getOrganizationByOrgDomain(domain.getUuid());
      result.setLoginOrganization(org);

    } catch (Exception e) {
      result.addErrorText(e.getMessage());
    }
    return result;
  }

  public LoginResult login(String login, String password, String tokenValue, String domainCode)
      throws BusinessException {
    LoginResult lr = this.login(login, password, domainCode);
//    if (!lr.isError() && lr.getUser().getUseToken().booleanValue()) {
//      int returnCode = HDTokenAuthUtil.HDTKCheckEx(TokenConstants.ENTERPRISE_CODE,
//          TokenConstants.ENTERPRISE_PASSWORD, lr.getUser().getTokenSn(),
//          lr.getUser().getTokenPin(), tokenValue);
//      if (returnCode != 0) {
//        lr.addErrorText("令牌验证出错");
//        // lr.addErrorText(HDTokenAuthUtil.HDTKGetErrMsg(returnCode));
//      }
//    }
    return lr;
  }

  public void logout(IUser user) {
    // 注意: user可能是null
  }

  private IUser sysUser = null;

  public IUser getSysUser() throws BusinessException {
    if (sysUser != null) {
      return sysUser;
    }

    sysUser = new User();
    sysUser.setUuid("SYSUSER_UUID");
    try {
      IDomainMgr domainMgr = (IDomainMgr) NamingMgr.getInstance().lookupMgr(IDomainMgr.class);
      sysUser.setDomain(domainMgr.getRootDomain());
      sysUser.setLogin("**SYSUSER**");
      sysUser.setName("系统用户");
    } catch (HibernateException e) {
      throw new BusinessException("无法取得系统用户。" + e.getMessage());
    }
    return sysUser;
  }
}
